package com.bosssoft.trainee.nontax.service.imp;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.bosssoft.trainee.nontax.entity.po.User;
import com.bosssoft.trainee.nontax.service.TokenService;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author liuqiang
 * @date 2022/6/19 23:21
 */
@Service
public class TokenServiceImp implements TokenService {

    /**
     * JWT生产Token
     * JWT构成：header + payload + signature
     *
     * @param user user
     * @return token
     */
    public String getToken(User user) {

        Date start = new Date();
        long currentTime = System.currentTimeMillis() + 60 * 60 * 1000;//一小时有效时间
        Date end = new Date(currentTime);
        String token = "";
        token = JWT.create()
                .withAudience(user.getUserId().toString())
                .withIssuedAt(start)     //sign time
                .withExpiresAt(end)     //设置过期时间
                .sign(Algorithm.HMAC256(user.getUserPassword()));   //signature加密

        return token;
    }

    /**
     * 从请求头中获取id
     *
     * @return id
     */
    public String getUserId() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        String token = "";
        if (requestAttributes != null) {
            HttpServletRequest request = requestAttributes.getRequest();
            token = request.getHeader("token");// 从 http 请求头中取出 token
            return JWT.decode(token).getAudience().get(0);
        } else {
            return "0";
        }
    }
}
